<template>
  <div class="login-container bgImg content">
    <div class="layout">
      <div class="form-container">
        <div class="title">快乐の家</div>
        <a-tabs default-active-key="login" class="tabs" :tabBarGutter="35">
          <a-tab-pane key="login" tab="登录">
            <a-form-model :model="loginForm" :rules="loginRules" :wrapper-col="{ span: 22 }" ref="loginForm">
              <a-form-model-item prop="username">
                <a-input
                  v-model="loginForm.username"
                  placeholder="请输入账号"
                  size="large"
                  allow-clear
                  @pressEnter="focusPassword"
                >
                  <a-icon slot="prefix" type="user" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item prop="password">
                <a-input-password
                  v-model="loginForm.password"
                  placeholder="请输入密码"
                  size="large"
                  allow-clear
                  @pressEnter="toLogin"
                  ref="password"
                >
                  <svg-icon icon="password" :size="14" slot="prefix"> </svg-icon>
                </a-input-password>
              </a-form-model-item>
              <a-form-item style="margin-top:-7px">
                <a-button type="primary" block size="large" :loading="loading" @click="toLogin">
                  登录
                </a-button>
              </a-form-item>
              <a-form-item style="margin-top:-7px">
                <span class="forge-password pointer">忘记密码</span>
              </a-form-item>
            </a-form-model>
          </a-tab-pane>
          <a-tab-pane key="register" tab="注册">
            <a-form-model :model="registerForm" :rules="registerRules" :wrapper-col="{ span: 22 }" ref="registerForm">
              <a-form-model-item prop="register">
                <a-input
                  v-model="registerForm.username"
                  placeholder="请输入用户名"
                  size="large"
                  allow-clear
                  :maxLength="11"
                  type="text"
                >
                  <a-icon slot="prefix" type="user" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item>
                <a-input
                  v-model="registerForm.email"
                  placeholder="请输入验证邮箱"
                  size="large"
                  type="email"
                  @pressEnter="getCode"
                >
                  <a-icon slot="prefix" type="mail" theme="filled" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item prop="code">
                <a-input
                  v-model="registerForm.code"
                  placeholder="请输入验证码"
                  size="large"
                  :maxLength="6"
                  style="width:58%;"
                  ref="code"
                >
                </a-input>
                <a-button size="large" @click="getCode" :disabled="codeStatus" style="width:35%;margin-left:7%">{{
                  phoneCode
                }}</a-button>
              </a-form-model-item>
              <a-form-model-item has-feedback prop="password">
                <a-input
                  v-model="registerForm.password"
                  placeholder="请输入密码"
                  size="large"
                  type="password"
                  ref="password"
                >
                  <svg-icon icon="password" :size="14" slot="prefix"></svg-icon>
                </a-input>
              </a-form-model-item>
              <a-form-model-item has-feedback prop="confirmPassword">
                <a-input
                  v-model="registerForm.confirmPassword"
                  placeholder="确认密码"
                  size="large"
                  type="password"
                  ref="confirmPassword"
                >
                  <svg-icon icon="password" :size="14" slot="prefix"></svg-icon>
                </a-input>
              </a-form-model-item>
              <a-form-item style="margin-top:-7px">
                <a-button type="primary" block size="large" :loading="loading" @click="register">
                  注册
                </a-button>
              </a-form-item>
            </a-form-model>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
  </div>
</template>

<script>
import { isEmail, isPassWord} from '@/utils/validate';
import { getCache, setCache, removeCache } from '@/utils/session';
import { getPhoneCode } from '@/api/user';
export default {
  name: 'login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.trim().length === 0) {
        callback(new Error('用户名不能为空'));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (!isPassWord(value)) {
        callback(new Error('请正确输入密码'));
      } else {
        callback();
      }
    };
    const confirmPassword = (rule, value, callback) => {
      if (value.trim().length === 0) {
        callback(new Error('再次输入密码'));
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };

    return {
      currentTab: 'login',
      loginForm: {
        username: '',
        password: '',
        phone: '',
        code: '',
        remember: true
      },
      registerForm: {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      registerRules: {
        password: [{ required: true, trigger: 'change' }],
        confirmPassword: [{ required: true, trigger: 'change', validator: confirmPassword }]
      },
      loading: false,
      phoneCode: '获取验证码',
      codeStatus: false,
      currentCode: null
    };
  },
  mounted() {
    const cache = getCache('LOGIN_INFO');
    if (cache) {
      this.loginForm.username = cache.username;
      this.loginForm.password = cache.password;
    }
  },
  methods: {
    focusPassword() {
      this.$refs.password.focus();
    },
    //获取验证码
    getCode() {
      if (isEmail(this.registerForm.email)) {
        this.codeStatus = true;
        let time = 60;
        var getPhoneIntval = setInterval(() => {
          if (time > 0) {
            time--;
            this.phoneCode = `重新获取(${time}s)`;
          } else {
            clearInterval(getPhoneIntval);
            getPhoneIntval = null;
            this.phoneCode = '获取验证码';
            this.codeStatus = false;
          }
        }, 1000);

        this.$refs.code.focus();
        getPhoneCode({ email: this.registerForm.email }).then(res => {
          this.currentCode = res.data;
          setTimeout(() => {
            this.$notification.success(
              {
                message: '提示',
                description: '验证码获取成功，您的验证码为：' + res.data
              },
              12
            );
          }, 1000);
        });
      } else {
        this.$message.error('请正确输入手机号');
      }
    },
    //登录
    toLogin() {
      this.$refs.loginForm.validate(valid => {
        console.log('校验结果', valid);
        if (valid) {
          this.loading = true;
          if (this.currentTab === 'login') {
            const { username, password } = this.loginForm;
            console.log('执行登录', username, password);
            this.$store
              .dispatch('user/login', { username, password })
              .then(() => {
                if (this.loginForm.remember) {
                  setCache('LOGIN_INFO', { username, password });
                  let path = '/';
                  this.$router.push({
                    path: path
                  });
                  this.loading = false;
                } else {
                  removeCache('LOGIN_INFO');
                }
              })
              .catch(() => {
                let path = '/login';
                this.$router.push({
                  path: path
                });
                setTimeout(() => {
                  this.loading = false;
                }, 500);
                this.$message.error('用户名或密码错误');
              });
          } else if (this.currentTab === 'phone') {
            const { phone, code } = this.loginForm;
            this.$store
              .dispatch('user/codeTest', { phone, code })
              .then(() => {
                removeCache('LOGIN_INFO');
                this.$router.push({
                  path: '/'
                });
                this.loading = false;
              })
              .catch(() => {
                setTimeout(() => {
                  this.loading = false;
                }, 500);
              });
          }
        } else {
          return false;
        }
      });
    },
    register() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          const { username, password, email, code } = this.registerForm;
          this.$store
            .dispatch('user/register', { username, password, email, code })
            .then(res => {
              this.$message.success(res);
            })
            .catch(reason => {
              console.log('注册失败', reason);
              this.$message.error('注册失败:' + reason.data);
            });
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.login-container {
  background-image: url('~@/assets/login/background.jpg');
  .layout {
    width: 55%;
    min-width: 900px;
    margin: 0 auto;
    .form-container {
      width: 400px;
      height: 550px;
      margin: 0 auto;
      margin-right: 0;
      padding-top: calc(50vh - 249.5px);
      .title {
        font-weight: 700;
        font-size: 1.8rem;
        padding-left: 5px;
      }
      .tabs {
        margin: 15px 0;
      }
      .forge-password {
        font-size: 14px;
        float: right;
        color: #1890ff;
      }
    }
  }
}
</style>
<style lang="scss">
.login-container {
  .ant-tabs-bar {
    border-bottom: none !important;
  }
  .ant-input-affix-wrapper .ant-input:not(:first-child) {
    padding-left: 35px !important;
  }
  .ant-tabs-bar {
    margin-bottom: 30px !important;
  }
}
</style>
